package httpUtilsx

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"time"
)

func CreatHttpClient(proxyAddr ...string) *http.Client {
	httpTr := &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 100,
		IdleConnTimeout:     10 * time.Second,
	}

	if len(proxyAddr) > 0 {
		proxy, err := url.Parse(proxyAddr[0])
		if err != nil {
			log.Fatal(err)
		}
		httpTr.Proxy = http.ProxyURL(proxy)
	}
	//if proxyAddr != "" {
	//	proxy, err := url.Parse(proxyAddr)
	//	if err != nil {
	//		log.Fatal(err)
	//	}
	//	httpTr.Proxy = http.ProxyURL(proxy)
	//}
	return &http.Client{
		Timeout:   20 * time.Second,
		Transport: httpTr,
	}

}

type ReqConfig = func(req *http.Request)

func CreateReq(url string, method string, param io.Reader, headers ...ReqConfig) *http.Request {
	req, err := http.NewRequest(method, url, param)
	if err != nil {
		err = fmt.Errorf("create http request failed: %s", err.Error())
		panic("create http request failed:")
	}
	for _, header := range headers {
		header(req)
	}
	return req
}
